#include <string.h>
#include "String.h"
#include "MQTT/MQTTError.h"
#include "Core/Interface.h"

int32_t stringDup(char **dest, char *src) {

    if (*dest != NULL) {
        getSystemInterface()->memFree(*dest);
        *dest = NULL;
    }

    *dest = getSystemInterface()->memMalloc((uint32_t)(strlen(src) + 1));
    if (*dest == NULL) {
        return memoryMallocFailed;
    }

    memset(*dest, 0, strlen(src) + 1);
    memcpy(*dest, src, strlen(src));
    return aiotSuccess;
}

int32_t stringSprintf(char **dest, char *fmt, char *src[], uint8_t count) {

    char *buffer = NULL, *value = NULL;
    uint8_t idx = 0, percentIdx = 0;
    uint32_t bufferLen = 0;

    bufferLen += strlen(fmt) - 2 * count;
    for (percentIdx = 0; percentIdx < count; percentIdx++) {
        value = (*(src + percentIdx) == NULL) ? ("") : (*(src + percentIdx));
        bufferLen += strlen(value);
    }

    buffer = getSystemInterface()->memMalloc(bufferLen + 1);
    if (buffer == NULL) {
        return memoryMallocFailed;
    }

    memset(buffer, 0, bufferLen + 1);

    for (idx = 0, percentIdx = 0; idx < strlen(fmt);) {
        if (fmt[idx] == '%' && fmt[idx + 1] == 's') {
            value = (*(src + percentIdx) == NULL) ? ("") : (*(src + percentIdx));
            memcpy(buffer + strlen(buffer), value, strlen(value));
            percentIdx++;
            idx += 2;
        } else {
            buffer[strlen(buffer)] = fmt[idx++];
        }
    }

    *dest = buffer;
    return aiotSuccess;
}
